package com.yang.limit.factory;

import com.yang.limit.constant.Constant;
import com.yang.limit.constant.RequestLimitType;
import com.yang.limit.service.RequestLimitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RequestLimitFactory implements InitializingBean {

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            //将RequestLimitService的四个实现类添加至Map集合
            applicationContext.getBeansOfType(RequestLimitService.class).values().forEach(service -> Constant.REQUEST_LIMIT_SERVICE_MAP.put(service.getLimitType(), service));
        } catch (Exception e) {
            log.error("初始化限流策略异常", e);
        }
    }

    public RequestLimitService build(RequestLimitType type) {
        return Constant.REQUEST_LIMIT_SERVICE_MAP.get(type);
    }
}
